<template>
  <view class="charging-order">
    <view class="header" v-if="false">
      <uni-icons class="back-icon" type="left" size="20" @click="goBack" />
      <text class="title">充电订单</text>
    </view>

    <view class="status-banner">
      <!-- <uni-icons class="status-icon" type="info" size="24" color="#ffffff" /> -->
      <image
        v-if="order.payStatus === 0"
        class="status-icon"
        src="./../../static/img/unpay-icon.png"
        mode="aspectFit|aspectFill|widthFix"
      >
      </image>
      <image
        v-if="order.payStatus === 1"
        class="status-icon"
        src="./../../static/img/payed-icon.png"
        mode="aspectFit|aspectFill|widthFix"
      >
      </image>
      <text class="status-text">{{ getPayStatusCName(order.payStatus) }}</text>
    </view>

    <view class="content">
      <view class="section fee-info">
        <text class="section-title">费用信息</text>
        <view class="fee-item">
          <text class="fee-label">充电费用</text>
          <text class="fee-value">¥{{ fenToYuan(order.totalFee) }}</text>
        </view>
        <view class="fee-details" v-if="false">
          <text class="detail-item">电费¥0.00元</text>
          <text class="detail-item">服务费¥0.00元</text>
          <text class="detail-item">调峰电费¥0.00元</text>
        </view>
        <view class="total-fee">
          <text class="total-label">实付：</text>
          <text class="total-value">¥{{ fenToYuan(order.totalFee) }}</text>
        </view>
      </view>

      <view class="section terminal-info">
        <text class="section-title">终端信息</text>
        <view class="terminal-row" @click="showTerminalDetail">
          <view class="terminal-left">
            <text class="terminal-id">
              {{ pile?.EquipmentName || "" }}({{
                pile?.EquipmentID || ""
              }})</text
            >
            <text class="terminal-address">川开微网系统改造充电站</text>
          </view>
          <uni-icons type="right" size="16" color="#999999" />
        </view>
      </view>

      <view class="section charging-info" v-if="order.payStatus !== 2">
        <text class="section-title">充电信息</text>
        <view class="info-item" v-if="false">
          <text class="info-label">车牌号码</text>
          <view class="plate-number">
            <text>川ABB1844</text>
            <!-- <text class="verify-tag">车牌号已核对</text> -->
          </view>
        </view>
        <view class="charging-time">
          <view class="time-range">
            <text>{{
              order.chargeStartTime?.slice(5, 20).split("T").join(" ") || ""
            }}</text>
            <text class="separator">至</text>
            <text>{{
              order.chargeEndTime?.slice(5, 20).split("T").join(" ") || ""
            }}</text>
          </view>
          <view class="duration">
            <text class="duration-label">充电时长</text>
            <text class="duration-value">{{
              getChargeTime(order.chargeStartTime, order.chargeEndTime)
            }}</text>
          </view>
          <view class="power">
            <text class="power-label">充电度数</text>
            <text class="power-value">{{ order.totalPower }}度</text>
          </view>
        </view>
      </view>
    </view>

    <view class="footer" v-if="order.payStatus === 0">
      <button class="pay-button" type="primary" @click="handlePay(order)">
        确认支付
      </button>
    </view>
  </view>
</template>

<script lang="ts" setup>
import { computed } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import useOrderStore from "../../store/order";
import { getOrderListByOpenId, getPileDetail } from "../../utils/api/teld";
import usePileStore from "../../store/pile";
import { sendCreateOrder } from "../../utils/api/test";
import useUserStore from "../../store/user";

const orderStore = useOrderStore();
const userStore = useUserStore();
const order = computed(() => orderStore.currentOrder);
const pileStore = usePileStore();
const pile = computed(() => pileStore.currentPile);
console.log("order", order);
const goBack = () => {
  uni.navigateBack();
};

/**
 * 通过 outTradeNo 获取订单详情
 * @param no
 */
const fetchOrderDetail = (no) => {
  const data = {
    outTradeNo: no, //查询某openid下的订单，直接传空值即可
    openId: userStore.openid,
  };

  getOrderListByOpenId(data).then((res) => {
    console.log("res-order:", res);
    orderStore.setCurrentOrder(res[0]);
    fetchPileDetailData(res[0].connectorId);
  });
};
const getPayStatusCName = (status) => {
  const map = {
    0: "待支付",
    1: "已支付",
    2: "进行中",
  };
  return map[status];
};

const showTerminalDetail = () => {
  uni.navigateTo({ url: `/pages/pile/pile?id=${pile.value.EquipmentID}` });
};
/**
 * 获取订单详情
 * @param id
 */
const fetchPileDetailData = (id) => {
  console.log("deatil-page-pile-id:", id);

  if (!id) {
    return;
  }
  const data = {
    StationsInfo: {
      LastQueryTime: "",
      PageNo: 1,
      PageSize: 50,
    },
    StationStatus: {
      StationIDs: ["5101161213"],
    },
    //想要查询的桩编号
    ConnectorID: id,
  };
  getPileDetail(data).then((res) => {
    console.log("res-detail:", res);
    pileStore.updatePile(res);
  });
};

const convertMilliseconds = (ms) => {
  var seconds = Math.floor((ms / 1000) % 60);
  var minutes = Math.floor((ms / (1000 * 60)) % 60);
  var hours = Math.floor((ms / (1000 * 60 * 60)) % 24);

  return hours + "小时" + minutes + "分" + seconds + "秒";
};
const getChargeTime = (start, end) => {
  const s = new Date(start).getTime();
  const e = new Date(end).getTime();
  const result = convertMilliseconds(e - s);
  // console.log(result);
  return result;
};

const fenToYuan = (fen) => {
  if (!fen) {
    return 0;
  }
  // 检查是否为数字，如果不是则尝试转换为数字
  fen = fen * 1;
  if (typeof fen !== "number" || isNaN(fen)) {
    console.error("输入的分数不是一个有效的数字");
    return null; // 或者可以抛出错误：throw new Error('输入的分数不是一个有效的数字');
  }
  return fen / 100;
};

const handlePay = (order) => {
  const payload = {
    description: order.description || "充电订单",
    wxOpenId: order.openId,
    outTradeNo: order.outTradeNo,
    totalFee: order.totalFee, // 单位：分
  };
  console.log("payload:", payload);

  sendCreateOrder(payload).then((res) => {
    console.log("res:", res);

    uni.requestPayment({
      provider: "wxpay",
      signType: "RSA",
      package: res.packageVal,
      ...res,

      success: function (res) {
        console.log("success:" + JSON.stringify(res));
        uni.navigateBack();
        // fetchOrderList();
      },
      fail: function (err) {
        console.log("fail:" + JSON.stringify(err));
      },
    });
    if (res.data.code == 500) {
      uni.showToast({
        title: "订单创建失败! " + res.data.msg,
        icon: "none",
      });
    }
  });
};

// onMounted(() => {
//   fetchOrderDetail(order);
// });

onLoad((options) => {
  console.log("detail-page-options:", options);

  if (options.outTradeNo) {
    // 根据 id 获取商品详情数据
    fetchOrderDetail(options.outTradeNo);
  }
});
</script>

<style lang="scss">
page {
  height: 100%;
  background-color: #f5f5f5;
}

.charging-order {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header {
  position: relative;
  height: 88rpx;
  display: flex;
  align-items: center;
  background-color: #ffffff;
  padding: 0 32rpx;
}

.back-icon {
  width: 20px;
  height: 20px;
}

.title {
  font-size: 16px;
  color: #333333;
  margin-left: 24rpx;
  font-weight: 500;
}

.status-banner {
  height: 65px;
  background-image: linear-gradient(270deg, #008df1 0%, #81bcff 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 32rpx;
}

.status-icon {
  width: 56px;
  height: 40px;
}

.status-text {
  color: #ffffff;
  font-size: 16px;
  margin-left: 16rpx;
}

.content {
  flex: 1;
  overflow: auto;
  padding: 0 16px;
}

.section {
  // background-color: #tras;
  border-bottom: 1px solid #bfbfc1;
  padding: 32rpx;
}

.section-title {
  display: inline-block;
  font-weight: bold;
  font-size: 16px;
  color: #282a31;
  margin-bottom: 8px;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16rpx;
}

.fee-label {
  font-size: 14px;
  color: #333333;
}

.fee-value {
  font-size: 14px;
  color: #333333;
}

.fee-details {
  display: flex;
  gap: 16rpx;
  margin-bottom: 24rpx;
}

.detail-item {
  font-size: 12px;
  color: #999999;
}

.total-fee {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.total-label {
  font-size: 14px;
  color: #333333;
}

.total-value {
  font-size: 16px;
  color: #333333;
  font-weight: 500;
}

.terminal-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.terminal-left {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.terminal-id {
  font-size: 14px;
  color: #333333;
}

.terminal-address {
  font-size: 12px;
  color: #999999;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 24rpx;
}

.info-label {
  font-size: 14px;
  color: #333333;
}

.plate-number {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.verify-tag {
  font-size: 12px;
  color: #00c853;
}

.charging-time {
  display: flex;
  flex-direction: column;
  gap: 16rpx;
}

.time-range {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 16rpx;
  font-size: 14px;
  color: #333333;
}

.separator {
  color: #999999;
}

.duration,
.power {
  display: flex;
  justify-content: space-between;
}

.duration-label,
.power-label {
  font-size: 14px;
  color: #7e7f83;
}

.duration-value,
.power-value {
  font-size: 16px;
  font-weight: bold;
  color: rgba(40, 42, 49, 1);
}

.footer {
  padding: 32rpx;
  background-color: #ffffff;
  box-shadow: 0px -4px 16px 1px rgba(0, 0, 0, 0.08);
}

.pay-button {
  background-color: #00c853 !important;
  color: #ffffff !important;
  font-size: 16px;
  height: 88rpx;
  line-height: 88rpx;
  margin: 0;
}
</style>
